package com.lagou.studentsystem.servlet;

import com.lagou.studentsystem.model.Student;
import com.lagou.studentsystem.model.User;
import com.lagou.studentsystem.service.StudentService;
import com.lagou.studentsystem.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "FindStudentServlet", urlPatterns = "/findStudentByidOrName")
public class FindStudentByIdOrNameServlet extends HttpServlet {

    private StudentService studentService = new StudentServiceImpl();
    List<Student> studentList = null;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
            String s_code = request.getParameter("id");
            String s_username = request.getParameter("name");
            if (null != s_code && !(s_code.equals("")) ) {
                Student student = studentService.getStudentById(s_code);
                if (null != student) {
                    studentList = new ArrayList<>();
                    studentList.add(student);
                    request.getSession().setAttribute("studentList", studentList);
                    response.sendRedirect("main.jsp");
                }
            } else if (null != s_username ) {
                List<Student> studentByName = studentService.getStudentByName(s_username);
                if (null != studentByName) {
                    request.getSession().setAttribute("studentList", studentByName);
                    response.sendRedirect("main.jsp");
                }
            }

        }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
